package com.fauks.ee.freemarker;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;

/**
 * 获取数据库相关信息工具类
 */
public class TableUtils {

    public static final String DRIVER_CLASS = PropertiesUtils.get("db.properties", "jdbc.driverClass");
    public static final String URL = PropertiesUtils.get("db.properties", "jdbc.url");
    public static final String USERNAME = PropertiesUtils.get("db.properties", "jdbc.username");
    public static final String PASSWORD = PropertiesUtils.get("db.properties", "jdbc.password");

    //获取数据库元信息
    public static DatabaseMetaData getDbMetaData() throws Exception {
        Class.forName(DRIVER_CLASS);
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return connection.getMetaData();
    }

    //获取数据库所有表名
    public static void getTable() {
        try {

            ResultSet tables = getDbMetaData().getTables(null, null, null, new String[]{"TABLE"});
            while (tables.next()) {
                //获取数据库所有表名
                String table_name = tables.getString("TABLE_NAME");
                System.out.println(table_name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取指定表的所有字段属性
    public static void getColumn(String tableName) {
        try {
            ResultSet columns = getDbMetaData().getColumns(null, "%", tableName, "%");
            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME");
                String typeName = columns.getString("type_name");
                String remarks = columns.getString("REMARKS");
                System.out.print("columnName==>" + columnName + "   ");
                System.out.print("typeName==>" + typeName + "   ");
                System.out.print("remarks==>" + remarks + "   ");
                System.out.println("====");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        //getTable();
        getColumn("itrip_label_dic");
    }
}
